package com.siwei.mes.service.laboratory.factory.material.admixtrue;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.concreteAdmixture.ConcreteAdmixtureHgl;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.concreteAdmixture.DataWjjHgl;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.AdmixtureLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.DataDefUcLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 外加剂-含固量
 *
 * @Description: 外加剂-含固量
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 22:09
 */
@Service
public class AdmixtureHglFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private AdmixtureLaboratoryMapper admixtureLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private DataDefUcLaboratoryMapper dataDefUcLaboratoryMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_HGL;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【外加剂-{}】", testProjectEnum.getName());
        ConcreteAdmixtureHgl concreteAdmixtureHgl = objJson.toJavaObject(ConcreteAdmixtureHgl.class);
        if (concreteAdmixtureHgl == null) {
            log.info("外加剂-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }

        DataWjjHgl dataWjjHgl = new DataWjjHgl();
        dataWjjHgl.setAVGHGL(NullUtils.ifNullBigDecimal(concreteAdmixtureHgl.getPjhgl()));
        dataWjjHgl.setConclusion(NullUtils.ifNull(concreteAdmixtureHgl.getDxjl()));
        dataWjjHgl.setSUBMITCSKZZ(NullUtils.ifNullBigDecimal(concreteAdmixtureHgl.getSccjkzz1()));
        dataWjjHgl.setSubmitcskzzCopy(NullUtils.ifNullBigDecimal(concreteAdmixtureHgl.getSccjkzz2()));

        ConcreteAdmixtureHgl.SyInfo sy1Info = concreteAdmixtureHgl.getSy1Info();
        if (sy1Info != null) {
            dataWjjHgl.setS1P1(NullUtils.ifNullBigDecimal(sy1Info.getClp()));
            dataWjjHgl.setS1HGL(NullUtils.ifNullBigDecimal(sy1Info.getHgl()));
            dataWjjHgl.setS1M1(NullUtils.ifNullBigDecimal(sy1Info.getSyzl()));
            dataWjjHgl.setS1M2(NullUtils.ifNullBigDecimal(sy1Info.getHghzl()));
        }

        ConcreteAdmixtureHgl.SyInfo sy2Info = concreteAdmixtureHgl.getSy2Info();
        if (sy1Info != null) {
            dataWjjHgl.setS2P1(NullUtils.ifNullBigDecimal(sy2Info.getClp()));
            dataWjjHgl.setS2HGL(NullUtils.ifNullBigDecimal(sy2Info.getHgl()));
            dataWjjHgl.setS2M1(NullUtils.ifNullBigDecimal(sy2Info.getSyzl()));
            dataWjjHgl.setS2M2(NullUtils.ifNullBigDecimal(sy2Info.getHghzl()));
        }

        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataWjjHgl, "化学检测室", concreteAdmixtureHgl.getJcrq(), detail);

        //根据样品编码查询外加剂含固量
        Map<String, Object> data_ycl_fmh_adxBySampleNo = admixtureLaboratoryMapper.findDATA_JGCL_WJJII_HGL_GBTBySampleNo(sampleNo);
        //查询没值说明需要  新增外加剂含固量
        if (data_ycl_fmh_adxBySampleNo == null) {
            admixtureLaboratoryMapper.addDATA_JGCL_WJJII_HGL_GBT(dataWjjHgl);
        } else {
            //修改外加剂含固量
            admixtureLaboratoryMapper.updateDATA_JGCL_WJJII_HGL_GBT(dataWjjHgl);
        }


        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        for (String str : set) {
            DataDefaultUc defaultUc = new DataDefaultUc();

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            String jcrq = concreteAdmixtureHgl.getJcrq();

            defaultUc.setConclusion(concreteAdmixtureHgl.getDxjl());
            defaultUc.setUcResultValue(concreteAdmixtureHgl.getDxjl());
            defaultUc.setUcTestValue(concreteAdmixtureHgl.getPjhgl());

            defaultUc.setUcUnit("%");

            if (StringUtils.isNotBlank(concreteAdmixtureHgl.getSccjkzz1()) && StringUtils.isNotBlank(concreteAdmixtureHgl.getSccjkzz2())) {
                double standardValue = Double.parseDouble(concreteAdmixtureHgl.getSccjkzz1()) - Double.parseDouble(concreteAdmixtureHgl.getSccjkzz2());
                double standardValue2 = Double.parseDouble(concreteAdmixtureHgl.getSccjkzz1()) + Double.parseDouble(concreteAdmixtureHgl.getSccjkzz2());
                defaultUc.setUcStandardValue(standardValue + "～" + standardValue2);
            }


            //根据物料信息设置判断配置
            for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                if (TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_HGL.getCode().equals(test.getTestProjectCode())) {
                    if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                        String json = test.getObjJson();
                        super.setUcStandardValue(defaultUc, json, "hgl");
                    }
                }
            }


            //赋值
            super.setDefUc(defaultUc, experiment, "化学检测室", sampleNo, jcrq, detail);

            defaultUc.setUcParameterID(parameterID);//项目id

            //新增或修改DataDefaultUc
            super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载到协会数据库：【外加剂-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        //将json转成对象
        ConcreteAdmixtureHgl concreteAdmixtureHgl = objJson.toJavaObject(ConcreteAdmixtureHgl.class);
        if (concreteAdmixtureHgl == null) {
            log.info("外加剂-【{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }
        //根据样品编码查询矿渣粉密度
        Map<String, Object> data = admixtureLaboratoryMapper.findDATA_JGCL_WJJII_HGL_GBTBySampleNo(sampleNo);
        if (data == null) {
            log.info("外加剂-【{}】数据为空，跳过下载！sampleNo：{}", testProjectEnum.getName(), sampleNo);
            return null;
        }
        ConcreteAdmixtureHgl.setValue(concreteAdmixtureHgl, data);

        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }
        for (String str : set) {

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            //查询data_defalutUc 是否存在
            Map<String, Object> ucData = dataDefUcLaboratoryMapper.findDATA_DefaultUCBySampleNo(sampleNo, parameterID);
            if (ucData == null) {
                continue;
            }
        /*    String uCStandardValue = ucData.get("UCStandardValue").toString();
            if(StringUtils.isNotBlank(uCStandardValue)){
                String[] kzzList = uCStandardValue.split("～");
                if(kzzList != null){
                    if(kzzList.length > 0){
                        concreteAdmixtureHgl.setSccjkzz1(kzzList[0]);
                    }
                    if(kzzList.length > 0){
                        concreteAdmixtureHgl.setSccjkzz2(kzzList[1]);
                    }
                }
            }*/
        }
        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(concreteAdmixtureHgl);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.get("Equipment")));
        detail.setTemperature(NullUtils.ifNull(data.get("Temperature")));
        detail.setHumidness(NullUtils.ifNull(data.get("Humidity")));
        detail.setExperimentGist(NullUtils.ifNull(data.get("DetectonRuleCode")));
        detail.setJudgeGist(NullUtils.ifNull(data.get("AccessRuleCode")));

        experimentDetailMapper.updateByPrimaryKeySelective(detail);
        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
